<template>
  <div class="app-container">
    <div class="filter-container">
      <el-autocomplete
        v-model="listQuery.addressName"
        :fetch-suggestions="loadCities"
        placeholder="请选择城市"
        class="filter-item"
        @select="handleSelect">
      </el-autocomplete>

      <el-input v-model="listQuery.phone" placeholder="请输入手机号" style="width: 200px;" class="filter-item"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
      <template slot-scope="{row}">
        <span>{{ row.id }}</span>
      </template>
    </el-table-column>
      <el-table-column label="城市" prop="address" align="center">
        <template slot-scope="{row}">
          <span>{{ getCityName(row.address) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓" prop="driverSurname" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverSurname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="driverName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" prop="driverPhone" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="driverGender" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverGender == 1 ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="城市" prop="address">
          <el-autocomplete
            v-model="temp.addressName"
            :fetch-suggestions="loadCities"
            placeholder="请选择城市"
            class="filter-item"
            @select="handleSelectUpdate">
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="姓" prop="driverSurname">
          <el-input v-model="temp.driverSurname" />
        </el-form-item>
        <el-form-item label="姓名" prop="driverName">
          <el-input v-model="temp.driverName" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="电话" prop="driverPhone">
          <el-input v-model="temp.driverPhone" />
        </el-form-item>
        <el-form-item label="性别" prop="driverGender">
          <el-radio-group v-model="temp.driverGender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createDate():UpdateDate()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createOrUpdateDriverUser, getDicDistrict } from '@/api/driverUser.js'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'driver',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      filteredCities: {}, // 存储筛选后的城市
      cityNameToCode: {}, // 用于存储城市名称到编码的映射
      cityCodeToName: {}, // 用于存储城市编码到名称的映射
      temp: {
        address:"",
        addressName: "",
        driverSurname: "",
        driverName: "",
        driverPhone: "",
        driverGender: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      downloadLoading: false
    }
  },
  created() {
    this.getDicDistrict();
    this.getList();
  },
  methods: {
    getDicDistrict() {
      getDicDistrict().then(resp => {
        const data = resp.data;
        const cityNameToCode = {};
        const cityCodeToName = {};
        for (const item of data) {
          cityNameToCode[item.addressName] = item.addressCode;
          cityCodeToName[item.addressCode] = item.addressName;
        }
        this.cityNameToCode = cityNameToCode;
        this.cityCodeToName = cityCodeToName;
      });
    },
    
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getCityName(cityCode) {
      return this.cityCodeToName[cityCode];
    },

    loadCities(queryString, cb) {
      if (queryString === '') {
        cb(this.cityNameToCode.map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] })));
      } else {
        const results = Object.keys(this.cityNameToCode)
          .filter(city => city.includes(queryString))
          .map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] }));
        cb(results);
      }
    },

    handleSelect(item) {
      // 更新显示值为城市名称
      this.listQuery.addressName = item.value;
      // 同时更新实际的城市代码
      this.listQuery.address = item.code;
    },

    handleSelectUpdate(item){
      this.temp.addressName = item.value;
      this.temp.address = item.code;
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 在添加时，清空 temp 对象，以确保不提交 ID
      this.temp = {
        address: "",
        addressName: "",
        driverSurname: "",
        driverName: "",
        driverPhone: "",
        driverGender: 1
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.temp = {
        id: row.id,
        address: row.address,
        addressName: this.getCityName(row.address),
        driverSurname: row.driverSurname,
        driverName: row.driverName,
        driverPhone: row.driverPhone,
        driverGender: row.driverGender
      };
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },

    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },

    createDate() {
      console.log(this.temp);
      createOrUpdateDriverUser(this.temp).then(() => {
        this.dialogFormVisible = false;
        this.getList();
      }).catch(error => {
        console.error('Failed to create item:', error);
      });
    },

    UpdateDate() {
      console.log(this.temp);
      createOrUpdateDriverUser(this.temp).then(() => {
        this.dialogFormVisible = false;
        this.getList();
      }).catch(error => {
        console.error('Failed to update item:', error);
      });
    },
  },

  watch: {
    'listQuery.addressName'(newVal) {
      // 当新值为空时，也将城市代码设置为空
      if (!newVal) {
        this.listQuery.address = '';
      }
    }
  }
}
</script>